<?php
/**
 * @link http://www.anabas.tk/awc/wiki
 *
 * @package Aba Sulution
 * @subpackage Aba_Core
 * @since Aba Core 1.0.1 beta
 */

defined( 'ABSPATH' ) or die(/*Nothing...*/);

abstract class AWC_Page_Options extends AWC_Settings_API implements IAWC_API{
    public $id_base = 'awc_page_settings';
    
    public $id      = '';
    
    public $page_title;
    
    public $menu_title;
    
    public $capability;
    
    public $position;
    
    public $icon_url;
    
    public $parent;
    
    public $group_title;
    
    public $args = array();
    
    public $help_tabs = array();
    
    public $help_sidebar = false;
    
    public $tabs = array();
    
    public $active = true;
    
    private $ready = false;
    
    private $type;
    
    private $current_screen;
    
    function __construct( $page_title, $menu_title, $capability, $icon_url, $position, /*$type = 'menu_page', */$group_title = false, $parent = false, $is_tab = false ){
        $this->id = sanitize_key( get_class( $this ) );
        $this->page_title = $page_title;
        $this->menu_title = $menu_title;
        $this->capability = $capability;
        $this->position   = $position;
        $this->icon_url   = $icon_url;
        //$this->type       = $type ? $type : 'menu_page';
        $this->parent     = $parent? sanitize_key($parent) : $parent;
        $this->group_title = $group_title;    
        
        $type = 'menu_page';
        if ( !empty( $parent ) ){
            if ( $is_tab )
                $type = 'tab_page';
            else
                $type = 'submenu_page';
        }            
        else{
            $type = 'menu_page';
        }  
             
        $this->type = $type;
        if ( $this->type == 'tab_page' ){
            add_filter( "filter_tabs_". sanitize_key( $parent ), array($this, '_add_tab'), 10, 1 );
        }
        $this->ready = true;
    }
    
    function is_active(){
        return $this->active;
    }
    
    function trigger(){
        if ( !$this->is_active() )
            return false;
        if ( empty( $this->args['icon'] ) )
            $this->args['icon'] = $this->icon_url;
            
        add_action( 'admin_menu', array( $this, '_init' ) );
        return true;        
    }
    
    function init_form(){
        wp_die( '@override AWC_Page_Options::init_form()' );
    }
    
    function _init(){
        if ( !$this->ready )
            throw new Exception( 'Please use abstract::__construct()' );
        $san_class = sanitize_key( get_class( $this ) );
        if ( $this->id != $san_class )
            $this->id = $san_class;
            
        //here begin get
        $tab = !empty( $_GET['tab'] ) ? $_GET['tab'] : false;
        if( $this->type != 'tab_page' )
            $this->tabs = $tabs = apply_filters( "filter_tabs_". $this->id, $this->tabs );
            
        $this->current_screen = $this->_find_tab( $tab );
        if ( !$this->current_screen ){
            if ( !current_user_can( $this->capability ) ){
                $this->current_screen = $this->_firt_tab_current_user_can();
            }
            else{
                $this->current_screen = $this;
            }
        }
        if ( !$this->current_screen ){
            $this->current_screen = $this;
        }            
                
        $callback = "add_$this->type";
        $has_parent = !empty( $this->parent );
        $args = array();
        if ( $has_parent && $this->type != 'menu_page' ){
            $args[] = $this->parent;                
        }
        $args[] = $this->page_title;
        if ( !empty( $this->group_title ) && $this->type == 'menu_page' )
            $args[] = $this->group_title;
        else
            $args[] = $this->menu_title;
        $args[] = $this->current_screen->capability ;
        $args[] = $this->id;
        $args[] = array( $this, 'output' );
        $args[] = $this->icon_url;
        $args[] = $this->position;
        
        
        if ( $this->type != 'tab_page')
            $help_page = call_user_func_array( $callback, $args );
        if ( $this->type == 'menu_page' && !empty( $this->group_title ) ){            
            $args[1] = $this->menu_title;
            array_unshift( $args, $this->id );
            if ( $this->type != 'tab_page' )
                $help_page = call_user_func_array( 'add_submenu_page', $args );
        }
        
        
        if ( $this->type != 'tab_page' )
            add_action('load-'.$help_page, array( $this->current_screen, '_add_help_tab' ) );
    }
    
    function output(){
        $count_tab = count( $this->tabs );        
            
        $intance = $this->current_screen;
        $intance->init_form();
        $intance->process_admin_options();
        
        if ( !isset( $intance->form_fields['submit'] ) ){
            $intance->form_fields['submit'] = array( 
                'button'    => 'primary',
                'text'      => 'Save Changes',
                'type'      => 'submit'
            );
        }
        $intance->init_settings();
        $intance->args = wp_parse_args( $intance->args, array(
            'bform'         => '<form method="post">',
            'eform'         => '</form>',
            'hide_title'    =>  1,
        ) );
        
        $title = $count_tab? $intance->menu_title : $intance->page_title;
        echo '<div class="wrap">';
        screen_icon();
        if ( $count_tab ){
            $tabs = $this->tabs;
            $tabs[$this->id] = $this;
            usort($tabs, function( $a, $b ){ return $a->position - $b->position; });
            echo '<h2 class="nav-tab-wrapper">';
            //echo '<a class="nav-tab ' . ( !$tab ? 'nav-tab-active':'' ) . '" href="?page=' . $this->id .'">' . $this->menu_title . '</a>';
            foreach ( $tabs as $tab_key => $tab_caption ) {
                $active = ( $this->current_screen->id == $tab_caption->id ) ? 'nav-tab-active' : '';
                if ( current_user_can( $tab_caption->capability ) ){
                    echo '<a class="nav-tab ' . $active . '" href="?page=' . $this->id . ( $tab_caption->id == $this->id? '' : ('&tab=' . $tab_caption->id ) ) . '">' . $tab_caption->menu_title . '</a>';        
                }
                else{
                    echo '<a class="nav-tab disabled" href="javascript:void(0);">' . $tab_caption->menu_title . '</a>';    
                }
            }
            echo '</h2>';
        }
        else
            echo '<h2>'. $title .'</h2>';
        $intance->admin_options();
        echo '</div>';
    }
    
    function _find_tab( $tab ){
        if ( $tab && isset( $this->tabs[$tab] ) ){
            return $this->tabs[$tab];                   
        }
        return false;
    }
    
    function _firt_tab_current_user_can(){
        $tabs = $this->tabs;
        usort( $tabs, function ( $a, $b ){ return $a->position - $b->position; } );
        foreach( $tabs as $tab_caption ){
            if ( current_user_can( $tab_caption->capability ) ){
                return $tab_caption;
            }
        }
        return false;
    }
    
    function _add_help_tab(){
        $screen = get_current_screen();
        
        // Add my_help_tab if current screen is My Admin Page
        foreach( $this->help_tabs as $tab ){
            $screen->add_help_tab( $tab );
        }
        
        if ( $this->help_sidebar )
            $screen->set_help_sidebar( $this->help_sidebar );
    }
    
    function add_tab( $class_tab ){
        
    }
    
    function _add_tab( $tabs ){
        $tabs[$this->id] = $this;
        return $tabs;
    }
    
    function add_help_tab( $id, $title, $content ){
        $tab = array(
            'id' => $id,
            'title' => $title
        );
        if ( $content !== false ){
            $tab['content'] = $content;
        }
        else{
            $tab['content'] = '';
        }
        if ( empty( $this->help_tabs ) )
            $this->help_tabs = array();
        $this->help_tabs[] = $tab;
    }
    
    function set_help_sidebar( $content ){
        $this->help_sidebar = $content;
    }
    
    function init_settings(){
        if ( ! empty( $this->settings ) )
            return;

        // Load form_field settings
        $settings = get_option( $this->id_base, null );
        
        $this->settings = isset($settings[ get_class( $this ) ])?$settings[ get_class( $this ) ]:array();

        if ( empty( $this->settings ) || ! is_array( $this->settings ) ) {

            $this->settings = array();

            // If there are no settings defined, load defaults
            if ( $this->form_fields )
                foreach ( $this->form_fields as $k => $v )
                    $this->settings[ $k ] = isset( $v['default'] ) ? $v['default'] : '';
        }

        if ( $this->settings && is_array( $this->settings ) ) {
           $this->settings = array_map( array( $this, 'format_settings' ), $this->settings );
        }
    }
    
    function process_admin_options(){
        if ( !current_user_can( $this->capability ) ) 
            return;
        $this->validate_settings_fields();
        
        if ( count( $this->errors ) ){
            add_action( 'admin_notices', array( $this, 'display_errors' ) );
            return;
        }
        
        if ( isset( $_POST[ $this->get_field_name( 'submit' ) ] ) ){
            $key = $this->id_base;
            $settings = get_option( $key );
            if ( empty( $settings ) || !is_array( $settings ) ){
                $settings = array();
            }
            $settings[get_class( $this )] = $this->sanitized_fields;
            if ( update_option( $key, $settings ) ){
                $this->settings = $this->sanitized_fields;
            }
        }
    }
    
    function display_errors(){
        if ( count( $this->errors ) <= 0 ) return;
        echo '<div class="error">';
        foreach( $this->errors as $error ){
            echo '<p>' . $error . '</p>';
        }
        echo '</div>';
    }
    
}
